package com.xu.cloud.common.filter;

import com.xu.cloud.common.constant.OrderConstant;
import com.xu.cloud.common.util.HttpServletUtil;
import com.xu.cloud.common.util.ServletLogUtil;
import com.xu.cloud.common.wrapper.XuCloudRequestWrapper;
import com.xu.cloud.common.wrapper.XuCloudResponseWrapper;
import org.springframework.core.annotation.Order;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 请求日志过滤器
 *
 * @author xuguan
 * @since 2025/1/5
 */
@Order(value = OrderConstant.REQUEST_LOGGING_FILTER_ORDER)
@WebFilter(description = "请求日志过滤器", urlPatterns = "/*")
@SuppressWarnings("NullableProblems")
public class ApiLoggingFilter extends BaseRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        ServletLogUtil.requestLog(request);
        if (HttpServletUtil.isJsonRequest()) {
            request = wrapRequest(request);
            ServletLogUtil.requestBodyLog((XuCloudRequestWrapper) request);
        }

        // response = wrapResponse(response);
        filterChain.doFilter(request, response);

        ServletLogUtil.responseLog(response);
        ServletLogUtil.resultLog(request);
        // ServletLogUtil.responseBodyLog((XuCloudResponseWrapper) response);
    }

    private static XuCloudRequestWrapper wrapRequest(HttpServletRequest request) {
        if (request instanceof XuCloudRequestWrapper) {
            return (XuCloudRequestWrapper) request;
        } else {
            return new XuCloudRequestWrapper(request);
        }
    }

    private static XuCloudResponseWrapper wrapResponse(HttpServletResponse response) {
        if (response instanceof XuCloudResponseWrapper) {
            return (XuCloudResponseWrapper) response;
        } else {
            return new XuCloudResponseWrapper(response);
        }
    }

    // private static ContentCachingRequestWrapper wrapRequest(HttpServletRequest request) {
    //     if (request instanceof ContentCachingRequestWrapper) {
    //         return (ContentCachingRequestWrapper) request;
    //     } else {
    //         return new ContentCachingRequestWrapper(request);
    //     }
    // }
    //
    // private static ContentCachingResponseWrapper wrapResponse(HttpServletResponse response) {
    //     if (response instanceof ContentCachingResponseWrapper) {
    //         return (ContentCachingResponseWrapper) response;
    //     } else {
    //         return new ContentCachingResponseWrapper(response);
    //     }
    // }
}
